package com.zoran.study.spring.validation.validator;



import com.zoran.study.spring.validation.constraint.Password;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Validates password.
 *
 * @author Winter Gao
 *
 */
public class PasswordValidator implements ConstraintValidator<Password, String> {

    private int min;

    private int max;

    private Pattern pattern;

    @Override
    public void initialize(Password constraintAnnotation) {
        min = constraintAnnotation.min();
        max = constraintAnnotation.max();

        validateParameters();

        final String regex = constraintAnnotation.pattern();
        if (regex == null || regex.trim().length() == 0) {
            throw new IllegalArgumentException("password pattern cannot be null or empty");
        }

        pattern = Pattern.compile(constraintAnnotation.pattern());
    }

    private void validateParameters() {
        if (min < 0) {
            throw new IllegalArgumentException("The min parameter cannot be negative");
        }

        if (max < min) {
            throw new IllegalArgumentException("The length cannot be negative");
        }

    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null) {
            return false;
        }

        if (value.length() < min || value.length() > max) {
            return false;
        }

        Matcher m = pattern.matcher(value);
        return m.matches();
    }

}
